﻿using System;
using System.IO;
using System.Windows.Forms;
using MentalAlchemy.Molecules;

namespace MentalAlchemy.Compounds
{
	/// <summary>
	/// [molecule]
	/// 
	/// Control which represents list of folders.
	/// </summary>
	public partial class FoldersListControl : UserControl
	{
		#region - Properties. -
		/// <summary>
		/// Defines whether to show "Add From File..." button.
		/// </summary>
		public bool AddFromFolderBtnVisible { 
			get
			{
				return AddFromFileBtn.Visible;
			}
			set
			{
				AddFromFileBtn.Visible = value;
			}
		}

		/// <summary>
		/// Name of the group box containing the folders list.
		/// </summary>
		public string Caption
		{
			get { return MainGroupBox.Text; }
			set { MainGroupBox.Text = value; }
		}

		/// <summary>
		/// Returns array of all folders presented in the list.
		/// </summary>
		public string[] Folders
		{
			get
			{
				var folders = new string[FoldersList.Items.Count];
				FoldersList.Items.CopyTo(folders, 0);
				return folders;
			}
			set
			{
				FoldersList.Items.Clear();
				FoldersList.Items.AddRange(value);
			}
		}
		#endregion

		#region - Constructor. -
		public FoldersListControl()
		{
			InitializeComponent();
		} 
		#endregion

		#region - Event handlers. -
		/// <summary>
		/// Adds folders listed in some filename to the existing folders list.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AddFromFileBtn_Click(object sender, EventArgs e)
		{
			var res = openFileDialog1.ShowDialog();

			if (res != DialogResult.OK) { return; }

			//
			// read data from file assuming that the file contains only paths relative to file's location.
			string filePath = Path.GetDirectoryName(openFileDialog1.FileName);
			var lines = FileIO.ReadAllLines(openFileDialog1.FileName);

			var files = new string[lines.Length];
			for (int i = 0; i < lines.Length; i++)
			{
				if (lines[i].Trim().Length == 0) continue;
				files[i] = Path.Combine(filePath, lines[i]);
			}

			Folders = files;
		}

		/// <summary>
		/// Adds selected folder to the existing list of folders.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void AddBtn_Click(object sender, EventArgs e)
		{
			var res = folderBrowserDialog1.ShowDialog();

			if (res != DialogResult.OK) { return; }

			FoldersList.Items.Add(folderBrowserDialog1.SelectedPath);
		}

		/// <summary>
		/// Clears folders list.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ClearBtn_Click(object sender, EventArgs e)
		{
			FoldersList.Items.Clear();
		}
		#endregion
	}
}
